package com.talkyun.openx.interceptor;

import com.talkyun.openx.server.core.AbstractInterceptor;
import com.talkyun.openx.server.core.ServiceContext;
import com.talkyun.openx.server.core.ServiceRequest;
import com.talkyun.openx.server.core.ServiceResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PerformanceInterceptor extends AbstractInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(PerformanceInterceptor.class);
    private static final String FLAG_BEGIN_TIME = "$ITP.B.TIME";
    private int threshold = 1000; // ms

    public void setThreshold(int threshold) {
        this.threshold = threshold;
    }

    @Override
    public void doMessageIn(ServiceRequest sr) {
        ServiceContext ctx = ServiceContext.get();
        ctx.put(FLAG_BEGIN_TIME, System.currentTimeMillis());
    }

    @Override
    public void doMessageOut(ServiceResponse sp) {
        ServiceContext ctx = ServiceContext.get();
        long now = System.currentTimeMillis();
        long run = now - ctx.getLong(FLAG_BEGIN_TIME, 0L);

        if (run > threshold) {
            logger.warn("!!! {} execute over threshold! {} ", ctx.get(FLAG_SR), run);
        }
    }
}